package com.yushu.authority.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.yushu.authority.mapper.PmOrgMapper;
import com.yushu.authority.pojo.bo.PmOrg;
import com.yushu.authority.pojo.bo.PmUser;
import com.yushu.authority.pojo.vo.PmOrgVO;
import com.yushu.authority.service.PmOrgService;
import com.yushu.common.execption.CgException;
import com.yushu.common.service.impl.YSBaseServiceImpl;
import com.yushu.common.shiro.ShiroUtil;
import com.yushu.common.util.date.DateUtils;
import com.yushu.common.util.pager.Pages;
import com.yushu.common.util.string.CamelCaseUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;

 

/**
 * 
 * @author test
 * @CreateDate 2020-12-03 15:47:25
 */
@Service("pmOrgService")
public class PmOrgServiceImpl extends YSBaseServiceImpl<PmOrgMapper, PmOrg> implements PmOrgService {
    @Autowired
    private RedisTemplate redisTemplate;

    public Pages<PmOrgVO> page(Pages<PmOrgVO> page) {
        PmUser sessionUser = ShiroUtil.getSessionUser();
        EntityWrapper wrapper = new EntityWrapper<PmOrgVO>();
        PmOrgVO pmOrg = page.getData();
        if (null != pmOrg) {
            if (StringUtils.isNotEmpty(pmOrg.getId())) {
                wrapper.like("t.id", pmOrg.getId(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(pmOrg.getPid())) {
                wrapper.like("t.p_id", pmOrg.getPid(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(pmOrg.getOrgName())) {
                wrapper.like("t.org_name", pmOrg.getOrgName(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(pmOrg.getOrgIntro())) {
                wrapper.like("t.org_intro", pmOrg.getOrgIntro(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(pmOrg.getOrgAddress())) {
                wrapper.like("t.org_address", pmOrg.getOrgAddress(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(pmOrg.getOrgCertificate())) {
                wrapper.like("t.org_certificate", pmOrg.getOrgCertificate(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(pmOrg.getOrgLeader())) {
                wrapper.like("t.org_leader", pmOrg.getOrgLeader(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(pmOrg.getOrgState())) {
                wrapper.like("t.org_state", pmOrg.getOrgState(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(pmOrg.getOrgCoder())) {
                wrapper.like("t.org_coder", pmOrg.getOrgCoder(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(pmOrg.getOrgPostcode())) {
                wrapper.like("t.org_postcode", pmOrg.getOrgPostcode(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(pmOrg.getOrgPhone())) {
                wrapper.like("t.org_phone", pmOrg.getOrgPhone(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(pmOrg.getOrgOrder())) {
                wrapper.like("t.org_order", pmOrg.getOrgOrder(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(pmOrg.getDeleteState())) {
                wrapper.like("t.delete_state", pmOrg.getDeleteState(), SqlLike.DEFAULT);
            }
            if (null != pmOrg.getCreateTimeBefore() && null != pmOrg.getCreateTimeAfter()) {
                String dateBefore = DateUtils.dateToString(pmOrg.getCreateTimeBefore());
                String dateAfter = DateUtils.dateToString(pmOrg.getCreateTimeAfter());
                wrapper.between("t.create_time", dateBefore, dateAfter);
            }

            if (null != pmOrg.getUpdateTimeBefore() && null != pmOrg.getUpdateTimeAfter()) {
                String dateBefore = DateUtils.dateToString(pmOrg.getUpdateTimeBefore());
                String dateAfter = DateUtils.dateToString(pmOrg.getUpdateTimeAfter());
                wrapper.between("t.update_time", dateBefore, dateAfter);
            }
            if (StringUtils.isNotEmpty(pmOrg.getCreateUserId())) {
                wrapper.like("t.create_user_id", pmOrg.getCreateUserId(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(pmOrg.getUpdateUserId())) {
                wrapper.like("t.update_user_id", pmOrg.getUpdateUserId(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(page.getSort())) {
                wrapper.orderBy(CamelCaseUtil.toUnderlineName(page.getSort()), "asc".equals(page.getOrder()));
            }
        }
        List<PmOrgVO> list = baseMapper.selectPageList(page, wrapper);
        page.setRecords(list);
        return page;
    }


    /**
     * 批量删除组织机构
     *
     * @param pmOrgs 组织结构
     * @return boolean
     */
   public boolean deleteBatch(List<PmOrg> pmOrgs) throws CgException {
        List<String> ids = null;
        boolean deleteState = false;
        try {
            ids = new ArrayList<String>();
            for (int i = 0; i < pmOrgs.size(); i++) {
                PmOrg pmOrg = pmOrgs.get(i);
                ids.add(pmOrg.getId());
            }
            deleteState = deleteBatchIds(ids);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CgException(e.getMessage());

        }
        return deleteState;
    }


    /**
     * 删除的时候同步组织机构的缓存数据
     *
     * @param id 主键
     * @return
     */
//    @CacheEvict(value = "pmOrg", key = "#id")
    @Override
    public boolean deleteById(Serializable id) {
        return super.deleteById(id);
    }

    /**
     * 通过主键更新组织机构的缓存数据
     *
     * @param pmOrg
     * @return
     */
    //@CachePut(value = "pmOrg",key = "#pmOrg.id")
    @Override
    public PmOrg updateByKey(PmOrg pmOrg) throws CgException {
        try {
            PmUser sessionUser = ShiroUtil.getSessionUser();
            pmOrg.setUpdateTime(new Date());
            super.updateById(pmOrg);
        } catch (RuntimeException e) {
            throw new CgException(e.getMessage());
        }
        return pmOrg;
    }

    /**
     * 保存的时候清除所有组织机构的缓存数据
     *
     * @param pmOrg
     * @return
     * @CacheEvict(value = "pmOrg", allEntries = true)
     */
    @Override
    public boolean insert(PmOrg pmOrg) throws CgException {
        try {
            PmUser sessionUser = ShiroUtil.getSessionUser();
            pmOrg.setId(IdWorker.get32UUID());
            /*yyyy-MM-dd HH:mm:ss*/
            pmOrg.setCreateTime(new Date());
            return super.insert(pmOrg);
        } catch (RuntimeException e) {
            throw new CgException(e.getMessage());
        }
    }



    /**
     * 查询时保存组织机构的缓存数据
     *
     * @param id 主键
     * @return
     * @Cacheable(value = "pmOrg", key = "#id")
     */
   @Override
    public PmOrg selectById(Serializable id) {
        return super.selectById(id);
    }


    @Override
    public PmOrgVO queryPmOrgByKey(String id) {
        return baseMapper.queryPmOrgByKey(id);
    }

     @Override
    public String checkRepeat(Map map) {
        String name = map.get("name") + "";
        String value = map.get("value") + "";
        String key = map.get("key") + "";

        int count = baseMapper.queryCountByName(map);
//        如果key存在，则是修改，否则是新增
        if (StringUtils.isNotBlank(key)) {
            /*如果是更新，则数字可以大于1*/
            if (count <= 0) {
                return "true";
            } else if (count > 1) {
                //说明存在多个
                return "false";
            } else if (count == 1) {

                EntityWrapper wrapper = new EntityWrapper<PmOrg>();
                wrapper.eq(name, value);
                List<PmOrg> pmOrgs = baseMapper.selectList(wrapper);
                String checkExit = "true";
                if (CollectionUtils.isNotEmpty(pmOrgs)) {
                    for (int i = 0; i < pmOrgs.size(); i++) {
                        PmOrg pmOrg = pmOrgs.get(i);
//                        说明当前值象存在于不同的对象之中，也不能重复
                        if (!StringUtils.equals(pmOrg.getId().trim(), key.trim())) {
                            checkExit = "false";
                        }
                    }
                }
                return checkExit;
            } else {
                return "true";
            }
        } else {
            /*如果是新增，则数字可以大于0*/
            if (count > 0) {
                return "false";
            } else {
                return "true";
            }
        }
    }

    @Override
    public List<PmOrg> selectList(PmOrg pmOrg) {
        EntityWrapper wrapper = new EntityWrapper<PmOrg>();
        if (StringUtils.isNotEmpty(pmOrg.getId())) {
            wrapper.eq("id", pmOrg.getId());
        }
        if (StringUtils.isNotEmpty(pmOrg.getPid())) {
            wrapper.eq("p_id", pmOrg.getPid());
        }
        if (StringUtils.isNotEmpty(pmOrg.getOrgName())) {
            wrapper.eq("org_name", pmOrg.getOrgName());
        }
        if (StringUtils.isNotEmpty(pmOrg.getOrgIntro())) {
            wrapper.eq("org_intro", pmOrg.getOrgIntro());
        }
        if (StringUtils.isNotEmpty(pmOrg.getOrgAddress())) {
            wrapper.eq("org_address", pmOrg.getOrgAddress());
        }
        if (StringUtils.isNotEmpty(pmOrg.getOrgCertificate())) {
            wrapper.eq("org_certificate", pmOrg.getOrgCertificate());
        }
        if (StringUtils.isNotEmpty(pmOrg.getOrgLeader())) {
            wrapper.eq("org_leader", pmOrg.getOrgLeader());
        }
        if (StringUtils.isNotEmpty(pmOrg.getOrgState())) {
            wrapper.eq("org_state", pmOrg.getOrgState());
        }
        if (StringUtils.isNotEmpty(pmOrg.getOrgCoder())) {
            wrapper.eq("org_coder", pmOrg.getOrgCoder());
        }
        if (StringUtils.isNotEmpty(pmOrg.getOrgPostcode())) {
            wrapper.eq("org_postcode", pmOrg.getOrgPostcode());
        }
        if (StringUtils.isNotEmpty(pmOrg.getOrgPhone())) {
            wrapper.eq("org_phone", pmOrg.getOrgPhone());
        }
        if (StringUtils.isNotEmpty(pmOrg.getOrgOrder())) {
            wrapper.eq("org_order", pmOrg.getOrgOrder());
        }
        if (StringUtils.isNotEmpty(pmOrg.getDeleteState())) {
            wrapper.eq("delete_state", pmOrg.getDeleteState());
        }
        if (StringUtils.isNotEmpty(pmOrg.getCreateUserId())) {
            wrapper.eq("create_user_id", pmOrg.getCreateUserId());
        }
        if (StringUtils.isNotEmpty(pmOrg.getUpdateUserId())) {
            wrapper.eq("update_user_id", pmOrg.getUpdateUserId());
        }
        List<PmOrg> list = selectList(wrapper);
        return list;
    }
    @Override
    public String validateOrgName(String orgName, String key) {
        EntityWrapper wrapper = new EntityWrapper<PmOrg>();
        wrapper.eq("org_name",orgName);
        String primaryKey = "";
        String validateInfo = super.validateNameRepeatByKey(key, primaryKey, wrapper);
        return validateInfo;
    }
}
